<template>
    <div>
        <div v-loading="loading" class="post-article">
            <div class="header">
                <el-select v-model="article.cid" placeholder="请选择文章栏目" style="width: 150px;" size="small">
                    <el-option
                            v-for="item in categories"
                            :key="item.id"
                            :label="item.cateName"
                            :value="item.id">
                    </el-option>
                </el-select>
                <el-input size="small" v-model="article.title" placeholder="请输入标题..." style="width: 400px;margin-left: 10px"></el-input>
                <el-tag
                        size="small"
                        :key="index"
                        v-for="(tag,index) in article.dynamicTags"
                        closable
                        :disable-transitions="false"
                        @close="handleClose(tag)" style="margin-left: 10px">
                    {{tag}}
                </el-tag>
                <el-input
                        class="input-new-tag"
                        v-if="tagInputVisible"
                        v-model="tagValue"
                        ref="saveTagInput"
                        size="small"
                        @keyup.enter.native="handleInputConfirm"
                        @blur="handleInputConfirm">
                </el-input>
                <el-button v-else class="button-new-tag" type="primary" size="small" @click="showInput">+Tag</el-button>
                <input type="file" ref="myfile" style="width: 200px;margin-left: 30px">
                <el-popover
                        placement="bottom"
                        trigger="hover">
                    <div style="width: 100px;height: 150px">
                        <img :src="article.articleImg" style="width: 150px;height: 150px">
                    </div>
                    <el-button slot="reference" @click="importData" type="success" size="mini" icon="el-icon-upload2">上传页面图片</el-button>
                </el-popover>

            </div>
            <div class="main">
                <div id="editor">
                    <mavon-editor style="height: 100%;width: 100%;" ref="editor" @imgAdd="imgAdd"
                                  @imgDel="imgDel" v-model="article.mdContent"></mavon-editor>
                </div>
                <div style="display: flex;align-items: center;margin-top: 15px;justify-content: flex-end">
                    <template>
                        <el-button size="small" type="primary" @click="clearAll()">清空所有</el-button>
                        <el-button size="small" type="primary" v-show="article.mdContent != null && article.mdContent.length > 0" @click="clearContent">清空内容</el-button>
                        <el-button size="small" type="primary" v-show="article.mdContent != null && article.mdContent.length > 0 && this.article.id != -1" @click="saveBlog(0)">移入垃圾箱</el-button>
                        <el-button size="small" type="primary" v-show="article.mdContent != null && article.mdContent.length > 0" @click="saveBlog(2)">保存到草稿箱</el-button>
                        <el-button size="small" type="success" v-show="article.mdContent != null && article.mdContent.length > 0" @click="saveBlog(1)">直接发表</el-button>
                    </template>
                </div>
            </div>
        </div>
    </div>
</template>

<script>
    import {mavonEditor} from 'mavon-editor'
    import 'mavon-editor/dist/css/index.css'
    import {getRequest, uploadFileRequest} from "../../../utils/api";
    export default {
        components: {
            mavonEditor
        },
        data() {
            return {
                categories: [],
                tagInputVisible: false,
                tagValue: '',
                loading: false,
                from: -1,
                article: {
                    id: '-1',
                    articleImg : null,
                    dynamicTags: [],
                    title: '',
                    content: '',
                    cid: ''
                }
            }
        },
        mounted: function () {
            this.getCategories();//获取分类
            //判断是否时新建还是原有的基础上编辑
            let from = this.$route.query.from;
            this.form = from;
            if (from != null && from != '' && from != undefined) {
                //获取id后获取文章信息
                let id = this.$route.query.id;
                getRequest(`/admin/article/${id}`).then(resp =>{
                    if(resp){
                        this.article = resp.obj;
                        console.log('-----' +resp.obj)
                        this.article.dynamicTags = [];
                        let tags = resp.obj.tags;
                        if(tags != null){
                            for (var i = 0; i < tags.length; i++) {
                                this.article.dynamicTags.push(tags[i].tagName)
                            }
                        }
                    }
                })
            }else {
                //初始化数据
                this.article = {
                        id: '-1',
                        articleImg : '',
                        dynamicTags: [],
                        title: '',
                        content: '',
                        cid: ''
                }
            }
        },
        methods: {
            importData() {
                let myfile = this.$refs.myfile;
                let files = myfile.files;
                if(files.length < 1){
                    this.$message.error("上传图片不能为空！")
                    return;
                }
                let file = files[0];
                var formData = new FormData();
                formData.append("file", file);
                uploadFileRequest("/upload",formData).then(resp=>{
                    if (resp) {
                        console.log(resp.obj)
                        this.article.articleImg = resp.obj;
                        this.$message.success("上传成功，记得保存文章哦~")
                    }
                })
            },
            clearContent(){
                this.article.mdContent = '';
            },
            clearAll(){
                this.article ={
                        id: '-1',
                        articleImg :null,
                        dynamicTags: [],
                        title: '',
                        content: '',
                        cid: ''
                }
            },
            isNotNullORBlank(...args) {
                for (var i = 0; i < args.length; i++) {
                    var argument = args[i];
                    if (argument == null || argument == '' || argument == undefined) {
                        return false;
                    }
                }
                return true;
            },
            saveBlog(state){
                if (!(this.isNotNullORBlank(this.article.title, this.article.mdContent, this.article.cid))) {
                    this.$message({type: 'error', message: '数据不能为空!'});
                    return;
                }
                this.loading = true;
                this.postRequest("/admin/article/", {
                    id: this.article.id,
                    title: this.article.title,
                    mdContent: this.article.mdContent,
                    htmlContent: this.$refs.editor.d_render,
                    articleImg : this.article.articleImg,
                    cid: this.article.cid,
                    state: state,
                    dynamicTags: this.article.dynamicTags
                }).then(resp=> {
                    this.loading = false;
                    if (resp) {
                        this.article.id = resp;
                        if(state ==1){
                            this.clearAll();
                            this.$message({type: 'success', message: '发布成功!'});
                        }else if(state == 2){
                            this.$message({type: 'success', message: '保存成功!'});
                        }else{
                            this.clearAll();
                            this.$message({type: 'success', message: '移入垃圾箱成功!'});
                        }
                     }
                }).catch(error =>{
                    this.loading = false;
                    if(state ==1){
                        this.$message({type: 'success', message: '博客发布失败!'});
                    }else if(state == 2){
                        this.$message({type: 'success', message: '保存草稿失败!'});
                    }else{
                        this.$message({type: 'success', message: '移入垃圾箱失败!'});
                    }
                })
            },
            imgAdd(pos, $file){
                // 第一步.将图片上传到服务器.
                var formdata = new FormData();
                formdata.append('file', $file);
                uploadFileRequest("/upload", formdata).then(resp=> {
                    if (resp) {
                        this.$refs.editor.$imglst2Url([[pos, resp.obj]])
                    }
                });
            },
            imgDel(pos){

            },
            getCategories(){
                getRequest('/admin/category/').then(resp=> {
                    this.categories = resp;
                });
            },
            handleClose(tag) {
                this.article.dynamicTags.splice(this.article.dynamicTags.indexOf(tag), 1);
            },
            showInput() {
                this.tagInputVisible = true;
                this.$nextTick(() => {
                    this.$refs.saveTagInput.$refs.input.focus();
                });
            },
            handleInputConfirm() {
                let tagValue = this.tagValue;
                if (tagValue) {
                    this.article.dynamicTags.push(tagValue);
                }
                this.tagInputVisible = false;
                this.tagValue = '';
            }
        },

    }
</script>
<style>
    .post-article .main #editor {
        width: 100%;
        height: 450px;
        text-align: left;
    }

    .post-article .header {
        width: 100%;
        line-height: 50px;
        height: 50px;
        background-color: #ececec;
        margin-top: 10px;
        padding-left: 5px;
    }

    .post-article .main {
        /*justify-content: flex-start;*/
        padding-left: 5px;
        background-color: #ececec;
        padding-top: 0px;
    }

    .post-article  .header  .el-tag + .el-tag {
        margin-left: 10px;
    }

    .post-article .header .button-new-tag {
        margin-left: 10px;
        height: 32px;
        line-height: 30px;
        padding-top: 0;
        padding-bottom: 0;
    }

    .post-article .header .input-new-tag {
        width: 90px;
        margin-left: 10px;
        vertical-align: bottom;
    }

    .post-article {
        background-color: #FAFAFA;
    }
</style>